package com.jeasonzhao.commons.configuration;

import java.util.ArrayList;

import com.jeasonzhao.commons.db.helper.ConnectionStringHelper;
import com.jeasonzhao.commons.db.helper.ConnectionStringInfo;
import com.jeasonzhao.commons.db.helper.ConnectionStringKey;
import com.jeasonzhao.commons.utils.Algorithms;
import com.jeasonzhao.commons.xml.XMLNode;

public class ConfigurationHelper
{
    private ConfigurationHelper()
    {
        super();
    }

    public static final ConfigurationAppender getConfigurationAppender(XMLNode node)
    {
        ConfigurationAppender a = new ConfigurationAppender();
        a.setClassName(node.valueOf("class"));
        a.setFileName(node.valueOf("file","xml","xmlfile","fileName","src"));
        a.setMode((ConfigurationAppenderMode) ConfigurationAppenderMode.findConstant(
            ConfigurationAppenderMode.class
            ,node.valueOf("mode","load","loadmode")
            ,ConfigurationAppenderMode.Lazy));
        a.setSectionName(node.valueOf("section","sectionName","node","nodeName"));
        return a;
    }

    public static final ConnectionStringInfo getConnectionStringFromXMLNode(
        XMLNode node,boolean isCheckDatabaseId)
        throws ConfigurationException
    {
        if(null == node)
        {
            return null;
        }
        String strId = node.subItemOrValueOf("id","name","key","databaseId");
        String strDbms = node.subItemOrValueOf("dbms","databaseType","database");
        String strUserName = node.subItemOrValueOf("userid","username","user","usr","uid");
        String strPassword = node.subItemOrValueOf("password","pwd","userpwd");
        ConnectionStringInfo conn = ConnectionStringHelper.getInstance().getConnectionStringFromName(strDbms);
        if(null == conn)
        {
            throw new ConfigurationException("can not found DBMS named " + strDbms);
        }
        if(isCheckDatabaseId && Algorithms.isEmpty(strId))
        {
            throw new ConfigurationException("No database ID:" + node.toString());
        }
        ArrayList<ConnectionStringKey> keys = conn.getKeys();
        if(null != keys)
        {
            for(ConnectionStringKey s : keys)
            {
                String pv = node.subItemOrValueOf(s.getName());
                if(null == pv && null == s.getValue())
                {
                    throw new ConfigurationException("No parameter value for " + s.getName() + ":" + node.toString());
                }
                else
                {
                    conn.addParameterValue(s.getName(),null == pv ? s.getValue() : pv);
                }
            }
        }
        conn.setId(strId);
        conn.setUserId(strUserName);
        conn.setPassword(strPassword);
        return conn;
    }
}
